<template>
  <div class="app-container">
    <div>
      <el-cascader aria-label="课程类别" style="width: 300px;" size="small" class="filter-item" placeholder="请选课程类别"
        @change="queryList" v-model="viewModel.subjectid" :options="typeOptionsub"
        :props="{ checkStrictly: true, emitPath: false,expandTrigger: 'hover' }" filterable clearable></el-cascader>
      <!-- <el-cascader aria-label="课程等级" size="small" class="filter-item" placeholder="请选课程等级" @change="queryList" v-model="viewModel.leaveid" :options="typeOptionleave"
                        :props="{ checkStrictly: true, emitPath: false,expandTrigger: 'hover' }" filterable clearable>
      </el-cascader>-->
      <el-select v-model="viewModel.TeachTypeCode" size="small" @change="queryList" placeholder="请选择">
        <el-option v-for="item in TeachTypeList" :key="item.TypeCode" :label="item.label" :value="item.TypeCode">
        </el-option>
      </el-select>
      <el-input v-model="viewModel.Title" size="small" placeholder="课程名称" style="width: 200px;" class="filter-item"
        @keyup.enter.native="queryList" />
      <el-button type="primary" size="small" @click="queryList" icon="el-icon-search">查询</el-button>
      <el-button type="primary" size="small" @click="refreshList" icon="el-icon-refresh">刷新</el-button>
    </div>
    <el-table v-loading="loading" :header-cell-style="{background:'#eef1f6',color:'#606266'}" :data="modelList"
      style="width: 100%;margin-top:30px;" border @sort-change="sortChange">
      <el-table-column label="课程图片" prop="ImageUrl">
        <template slot-scope="scope">
          <img style="height: 80px;width: 140px" :src="scope.row.ImageUrl" />
        </template>
      </el-table-column>
      <el-table-column label="课程名称" prop="Title">
        <template slot-scope="scope">{{ scope.row.Title }}</template>
      </el-table-column>
      <el-table-column label="课程类别" prop="SubjectName">
        <template slot-scope="scope">{{ scope.row.SubjectName }}</template>
      </el-table-column>
      <el-table-column label="课程类型" prop="TeachTypeName">
        <template slot-scope="scope">{{ scope.row.TeachTypeName }}</template>
      </el-table-column>
      <!--  <el-table-column label="课程等级"  prop="LeaveName">
        <template slot-scope="scope">{{ scope.row.LeaveName }}</template>
      </el-table-column>
      <el-table-column label="课程总量" sortable="custom" prop="Total">
        <template slot-scope="scope">{{ scope.row.Total }}</template>
      </el-table-column>
      <el-table-column label="课程剩余量" sortable="custom" prop="Residues">
        <template slot-scope="scope">{{ scope.row.Residues }}</template>
      </el-table-column>-->
      <el-table-column label="上架状态" sortable="PutawayStatusStr" prop="PutawayStatus">
        <template slot-scope="scope">{{ scope.row.PutawayStatusStr}}</template>
      </el-table-column>
      <el-table-column label="上架者" prop="Putawaier">
        <template slot-scope="scope">{{ scope.row.Putawaier}}</template>
      </el-table-column>
      <el-table-column label="上架时间" sortable="PutawayTimeStr" prop="PutawayTime">
        <template slot-scope="scope">{{ scope.row.PutawayTimeStr}}</template>
      </el-table-column>
      <el-table-column align="center" width="260" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="handleEdit(scope)" icon="el-icon-edit">编辑</el-button>
          <el-button type="text" v-if="scope.row.PutawayStatus==2" size="mini" @click="handlePublish(scope,1)"
            icon="el-icon-top">上架</el-button>
          <el-button type="text" v-else size="mini" @click="handlePublish(scope,2)" icon="el-icon-bottom">下架</el-button>
          <el-button type="text" v-if="scope.row.PutawayStatus==2" size="mini" @click="goback(scope,2)"
            icon="el-icon-bottom">重新审核</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件：https://element.eleme.cn/#/zh-CN/component/pagination -->
    <div class="block" style="float:right;margin-top:15px;" v-if="viewModel.total>0">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="viewModel.page" :page-sizes="[10, 20, 30, 40,100]" :page-size="viewModel.pageSize"
        @prev-click="lastPage" @next-click="nextPage" background layout="total, sizes, prev, pager, next, jumper"
        :total="viewModel.total"></el-pagination>
    </div>

    <el-dialog :visible.sync="dialogVisible" :title="'编辑'" width="40%" :close-on-click-modal="false">
      <el-form :model="model" ref="model" :rules="rules" label-width="100px" label-position="right">
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程封面" prop="ImageUrl">
              <!-- <el-upload class="avatar-uploader" id="uploadimginput" :action="actionUrl" :show-file-list="false"
                  :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"><i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>-->
              <img v-if="model.ImageUrl" :src="model.ImageUrl" class="avatar" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="课程名称" prop="Title">
              <el-input v-model="model.Title" placeholder="课程名称" disabled="false"></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
               <el-form-item label="课程总量" prop="Total">
                <el-input-number v-model="model.Total" placeholder="课程总量" style="width:100%" :step="1" step-strictly :min="0"/>
              </el-form-item>
          </el-col>-->
          <!-- <el-col :span="6">
              <el-form-item label="是否推荐" prop="IsRecommend">
                  <el-switch v-model="model.IsRecommend" active-color="#13ce66"
                inactive-color="#8d8d96">
              </el-switch>
              </el-form-item>
          </el-col>-->
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="课程类别" prop="SubjectName">
              <!-- <el-input v-model="model.SubjectName" placeholder="科目类别" /> -->
              <el-cascader aria-label="课程类别" disabled="false" style="width:100%" placeholder="请选课程类别"
                v-model="model.SubjectID" :options="typeOptionsub"
                :props="{ checkStrictly: true, emitPath: false,expandTrigger: 'hover' }" filterable clearable>
              </el-cascader>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
              <el-form-item label="课程等级" prop="LeaveID">

                <el-cascader aria-label="课程等级"  style="width:100%"  placeholder="请选课程等级"   v-model="model.LeaveID" :options="typeOptionleave"
                        :props="{ checkStrictly: true, emitPath: false,expandTrigger: 'hover' }" filterable clearable>
                      </el-cascader>
              </el-form-item>
          </el-col>-->
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程类型" prop="TeachTypeName">
              <el-input v-model="model.TeachTypeName" placeholder="课程类型" disabled="false"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否热门" prop="IsHot">
              <el-switch v-model="model.IsHot" active-color="#13ce66" inactive-color="#8d8d96"></el-switch>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
              <el-form-item label="是否推荐" prop="IsRecommend">
                  <el-switch v-model="model.IsRecommend" active-color="#13ce66"
                inactive-color="#8d8d96">
              </el-switch>
              </el-form-item>
            </el-col>
             <el-col :span="12">
              <el-form-item label="是否热门" prop="IsHot">
                  <el-switch v-model="model.IsHot" active-color="#13ce66"
                inactive-color="#8d8d96">
              </el-switch>
              </el-form-item>
          </el-col>-->
        </el-row>
        <!-- <el-row>
              <el-col :span="12">
              <el-form-item label="开始时间" prop="StartTime">
                <el-input v-model="model.StartTime" placeholder="科目类别" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束时间" prop="EndTime">
                <el-input v-model="model.EndTime" placeholder="科目类别" />
              </el-form-item>
            </el-col>
          </el-row>
   <el-row>
              <el-col :span="24">
              <el-form-item label="开始时间" prop="SubjectName">
                <div class="block">
    <span class="demonstration">销售时间</span>
    <el-date-picker
      v-model="model.StartTime"
      type="datetimerange"
      align="right"
      start-placeholder="开始日期"
      end-placeholder="结束日期"
      :default-time="['12:00:00', '08:00:00']">
    </el-date-picker>
  </div>
              </el-form-item>
            </el-col>

        </el-row>-->
        <!-- <el-row>
            <el-col :span="24">
              <el-form-item label="授权" prop="RoleIdList">
                <el-select v-model="model.RoleIdList" multiple placeholder="请选择" style="width: 100%">
                  <el-option v-for="item in roleList" :key="item.id" :label="item.label" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row> -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="课程描述" prop="Description">
              <el-input :autosize="{ minRows: 4, maxRows: 9}" type="textarea" v-model="model.Description"
                placeholder="课程描述" />
            </el-form-item>
          </el-col>
        </el-row>

        <div style="text-align:right">
          <el-button type="danger" @click="dialogVisible=false">取消</el-button>
          <el-button type="primary" @click="confirmModel">确认</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import { deepClone } from "@/utils";
  import { getList, updateModel, publishModel, goback } from "@/api/product";
  import { GetDictionaryByPCode } from "@/api/dictionary";
  import { getAllRoleListWithOptions } from '@/api/role'

  const defaultModel = {
    Id: "",
    PrId: "",
    Title: "",
    ImageUrl: "",
    SubjectID: "",
    SubjectName: "",
    TeachTypeName: "",
    LeaveID: "",
    LeaveName: "",
    IsRecommend: "",
    IsHot: "",
    Description: "",
    Price: "",
    Total: "",
    Residues: "",
    Putawaier: "",
    PutawayTime: "",
    PutawayStatus: "",
    Creater: "",
    CreateTime: "",
    RoleIdList: []
  };

  export default {
    data() {
      var validateCount = (rule, value, callback) => {
        if (value > this.model.Total) {
          callback(new Error("课程剩余不能大于课程总量"));
        } else {
          callback();
        }
      };
      return {
        viewModel: {
          SubjectID: "",
          SubjectName: "",
          LeaveID: "",
          LeaveName: "",
          TeachTypeCode: "",
          page: 1,
          pageSize: 10,
          total: 0,
          Title: "",
          OrderBy: "PutawayTime", //排序字段
          SortDir: "DESC" //升序排序
        },
        model: Object.assign({}, defaultModel),
        modelList: [],
        typeOptionsub: [],
        TeachTypeList: [],
        typeOptionleave: [],
        dialogVisible: false,
        loading: true,
        dialogType: "new",
        labelPosition: "right",
        apiPre: process.env.VUE_APP_BASE_API,
        actionUrl: "",
        roleList: [],
        rules: {
          LeaveID: [
            { required: true, message: "请选择课程等级", trigger: "change" }
          ]
          // Total: [{ required: true, message: "请输入菜单名称", trigger: "blur" }]
        }
      };
    },
    created() {
      this.GetDictionaryByPCode("Subject")
      this.GetDictionaryByPCode1("Category")
      this.getList(this.viewModel)
      this.actionUrl = this.apiPre + "/Upload/UploadFiles"
      // this.getAllRoleList()
    },
    methods: {
      async getAllRoleList() {
        var res = await getAllRoleListWithOptions()
        if (res.code == 200)
          this.roleList = res.data
      },
      async GetDictionaryByPCode(ams) {
        const res = await GetDictionaryByPCode(ams);
        this.typeOptionsub = res.data;
      },
      async GetDictionaryByPCode1(ams) {
        const res = await GetDictionaryByPCode(ams);
        this.TeachTypeList = res.data;
        this.TeachTypeList.unshift({ TypeCode: "", label: "全部" });
      },
      async getList(viewModel) {
        const res = await getList(viewModel);
        this.modelList = res.data.ProductList;
        this.viewModel.total = res.data.TotalCount;
        this.loading = false;
      },
      queryList() {
        this.viewModel.page = 1;
        this.getList(this.viewModel);
      },
      refreshList() {
        this.viewModel.page = 1;
        this.getList(this.viewModel);
      },
      sortChange(data) {
        const { prop, order } = data;
        this.viewModel.OrderBy = prop;
        if (prop == null || prop == "") this.viewModel.OrderBy = "CreateTime";
        if (order === "ascending") {
          this.viewModel.SortDir = "asc";
        } else {
          this.viewModel.SortDir = "desc";
        }
        this.queryList();
      },
      lastPage(val) {
        this.viewModel.page = val;
      },
      nextPage(val) {
        this.viewModel.page = val;
      },
      handleSizeChange(val) {
        this.viewModel.pageSize = val;
        this.getList(this.viewModel);
      },
      handleCurrentChange(val) {
        this.viewModel.page = val;
        this.getList(this.viewModel);
      },
      handlePublish(scope, status) {
        var str = "上架";
        if (status == 2) str = "下架";
        this.$confirm("确认" + str + scope.row.Title + "?", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(async () => {
            const re = await publishModel(scope.row.Id, status);
            if (re.data) {
              this.$notify({
                title: "成功",
                type: "success",
                message: "操作成功!"
              });
              this.getList(this.viewModel);
            }
            else {
              this.$notify({
                title: "提示",
                type: "info",
                message: re.message
              });

            }
          })
          .catch(err => {
            console.error(err);
          });
      },
      goback(scope, status) {
        this.$confirm("确认打回重新审核" + scope.row.Title + "?", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(async () => {
            const re = await goback(scope.row.Id, status);
            if (re.data) {
              this.$notify({
                title: "成功",
                type: "success",
                message: "操作成功!"
              });
              this.getList(this.viewModel);
            }
            else {
              this.$notify({
                title: "提示",
                type: "info",
                message: re.message
              });

            }
          })
          .catch(err => {
            console.error(err);
          });
      },
      handleEdit(scope) {
        this.dialogType = "edit";
        this.dialogVisible = true;
        this.model = deepClone(scope.row);
        this.GetDictionaryByPCode("Subject");
        //  this.GetDictionaryByPCode1("Level");
        this.$nextTick(() => {
          this.$refs["model"].clearValidate(); //清空上次的错误验证提示
        });
      },
      async confirmModel() {
        //如果把验证失败弹出提示代码放在validate里面则不会弹出错误提示，直接走下面的更新操作代码
        var v;
        this.$refs["model"].validate(valid => {
          v = valid;
        });
        if (!v) {
          return false;
        }
        await updateModel(this.model);
        this.getList(this.viewModel);
        this.dialogVisible = false;
        this.$notify({
          title: "成功",
          type: "success",
          message: "操作成功!"
        });
      },
      handleAvatarSuccess(res, file) {
        //图片上传成功响应方法
        this.model.ImageUrl = res.data;
      },
      beforeAvatarUpload(file) {
        const isImg = file.type === "image/jpeg" || file.type === "image/png";
        const isLt2M = file.size / 1024 / 1024 < 4;

        if (!isImg) {
          this.$notify({
            title: "失败",
            message: "上传头像图片只能是 JPG/JPEG/PNG 格式!",
            type: "error",
            duration: 3000
          });
          return false;
        }
        if (!isLt2M) {
          this.$notify({
            title: "失败",
            message: "上传头像图片大小不能超过 4MB!",
            type: "error",
            duration: 3000
          });
          return false;
        }
        return isImg && isLt2M;
      }
    }
  };
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>